<?php

namespace App\Http\Controllers\V1\Admin;

use App\Models\V1\Admins;
use App\Models\V1\SysPermission;
use App\Models\V1\SysRole;
use Earnp\GoogleAuthenticator\GoogleAuthenticator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends BaseController
{

    /**
     * 用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){

        $query=Admins::query();

        $pageSize=$request->input('pageSize',10);
        $order=$request->input('order','desc');
        $sort=$request->input('sort','id');

        if($request->filled('username')){
            $query->where('username','like','%'.$request->input('username').'%');
        }
        if($request->filled('mobile')){
            $query->where('mobile',"like","%".$request->input('mobile')."%");
        }
        if($request->filled('state')){
            $query->where('state',$request->input('state'));
        }
        if($request->filled('begin_at')){
            $query->where('created_at','>=',$request->input('begin_at'));
        }
        if($request->filled('end_at')){
            $query->where('created_at','<=',$request->input('end_at'));
        }
        $query->orderBy($sort,$order);
        $data=$query->paginate($pageSize);
        $role_model=new SysRole();
        foreach ($data->items() as  &$value){
            $value->roles = $role_model->getRoles($value->id,$value->mch_id);
        }
        return ajax_output(200,"成功",$data);
    }

    /**
     * 选择商务
     * @param Request $request
     * @return void
     */
    public function selectList(Request $request){
        $query=Admins::query();
        $data=[];
        if($request->filled('keyword')){
            $query->where("username","like","%".$request->input('keyword')."%")->orWhere('nickname',"like","%".$request->input('keyword')."%");
            $data=$query->select('id as value','username as label')->get();
        }
        return ajax_output(200,"成功",$data);
    }

    /**
     * 新增用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request){
        try {
            DB::beginTransaction();
            $role_ids=$request->input('role_ids',[]);
            $admin_model=new Admins();
            $vo=$admin_model->create([
                'username'=>$request->input('username',""),
                'password'=>bcrypt($request->input('password',"")),
                'mobile'=>$request->input('mobile',""),
                'nickname'=>$request->input('nickname',""),
                'email'=>$request->input('email',""),
                'qq'=>$request->input('qq',""),
                'mch_id'=>$this->user->mch_id,
                'sex'=>1,
                'is_super'=>0,//非超级管理员
                'is_google_auth'=>$request->input('is_google_auth',0),
                'google_secret'=>$request->input('google_secret',""),
                'state'=>(int)$request->input('state',1),
                'remark'=>$request->input('remark',"")
            ]);
            //设置当前用户的用户组
            $role_model=new SysRole();
            $role_model->setRoles($role_ids,$vo->id,$vo->mch_id);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return ajax_output(300,"数据异常:".$e->getMessage());
        }
        return ajax_output(200,"成功");
    }


    /**
     * 更新用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request,$id){
        try {
            DB::beginTransaction();
            $role_ids=$request->input('role_ids',[]);
            $admin_model = new Admins();
            $vo = $admin_model->find($id);
            if (!$vo) {
                return ajax_output(300, "数据不存在");
            }
            $vo->update([
                'mobile' => $request->input('mobile', ""),
                'nickname' => $request->input('nickname', ""),
                'email' => $request->input('email', ""),
                'qq' => $request->input('qq', ""),
                'state' => (int)$request->input('state', 0),
                'remark' => $request->input('remark', "")
            ]);

            ///设置当前用户的用户组
            $role_model=new SysRole();
            $role_model->setRoles($role_ids,$vo->id,$vo->mch_id);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return ajax_output(300,"数据异常:".$e->getMessage());
        }
        return ajax_output(200,"成功");
    }

    /**
     * 用户详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show(Request $request,$id){
        $admin_model=new Admins();
        $vo=$admin_model->find($id);

        //查询用户的角色
        $role_model=new SysRole();
        $roles=$role_model->getRoles($vo->id,$vo->mch_id);
        $role_ids=[];
        foreach($roles as $role){
            $role_ids[]=$role->id;
        }
        $vo->role_ids=$role_ids;
        return ajax_output(200,"成功",$vo);
    }

    /**
     * 重置密码
     * @param Request $request
     * @return void
     */
    public function resetPwd(Request $request){
        $password=$request->input('password');
        $userId=$request->input('userId',0);
        $admin_model=new Admins();
        $vo=$admin_model->find($userId);
        $vo->password=bcrypt($password);
        $vo->save();
        return ajax_output(200,"成功");
    }

    /**
     * 修改状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeStatus(Request $request){
        $userId=$request->input('userId',0);
        $admin_model=new Admins();
        $vo=$admin_model->find($userId);
        if(!$vo){
            return ajax_output(300,"数据不存在");
        }
        $vo->state=(int)$request->input('status',1);
        $vo->save();
        return ajax_output(200,"成功");
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInfo(Request $request){
        //查询用户的角色
        $role_model=new SysRole();
        $roles=$role_model->getRoles($this->user->id,$this->user->mch_id);
        $role_keys=$permissions_array=$allow_permissions=[];
        $permission_model=new SysPermission();
        foreach($roles as $role){
            $role_keys[]=$role->title;
            list($node,$permissions) = $permission_model->getPermissions($role->id);
            $permissions_array=array_merge($permissions_array,$permissions);
        }

        foreach($permissions_array as $row){
            if(!empty($row[1])){
                $allow_permissions[]=$row[1];
            }
        }
        //查询当前用户权限
        $data=[
            'user'=>$this->user,
            'roles'=>['admin'],//$role_keys,
            'permissions'=>["*:*:*"]//$allow_permissions//$allow_permissions//
        ];
        return ajax_output(200,"成功",$data);
    }

    /**
     * 个人信息
     * @param Request $request
     * @return void
     */
    public function profile(Request $request){
        $admin_model=new Admins();
        $vo=$admin_model->select('username','mobile','nickname','email','qq','avatar','sex','is_google_auth','google_secret')->find($this->user->id);

        // 获取google秘钥
        if(empty($vo->google_secret)){
            $google =GoogleAuthenticator::CreateSecret();
            $vo->google_secret=$google['secret'];
        }
        return ajax_output(200,"成功",$vo);
    }

    /**
     * 保存个人信息
     * @param Request $request
     * @return void
     */
    public function save_profile(Request $request){
        $admin_model=new Admins();
        $vo=$admin_model->find($this->user->id);
        $vo->update([
            'mobile'=>$request->input('mobile',""),
            'nickname'=>$request->input('nickname',""),
            'avatar'=>$request->input('avatar',""),
            'email'=>$request->input('email',""),
            'qq'=>$request->input('qq',""),
            'is_google_auth'=>$request->input('is_google_auth',0),
            'sex'=>$request->input('sex',0),
            'google_secret'=>$request->input('google_secret',"")
        ]);
    }

    /**
     * 修改密码
     * @param Request $request
     * @return void
     */
    public function updatePwd(Request $request){
        $admin_model=new Admins();
        $vo=$admin_model->find($this->user->id);
        $isCheck =\Hash::check($request->input('oldPassword'), $vo->password);
        if(!$isCheck) {//验证旧密码是否正确
            return ajax_output(300,"您输入的旧密码不正确，请重新输入");
        }
        $vo->password=bcrypt($request->input('newPassword'));
        $vo->save();
        return ajax_output(200,"成功");
    }


    /**
     * 获取当前用户的路由情况
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getRouters(Request $request){
        $permission_model=new SysPermission();
        ////权限修改修改
        $this->user->id = 4;//多加的
        $permission_menus=$permission_model->getPermissionMenu($this->user->id);
        return ajax_output(200,"成功",$permission_menus);
    }

    /**
     * 获取用户权限
     * @param Request $request
     * @return void
     */
    public function permissions(Request $request){
        $user_id=$request->input('user_id',0);
        $role_model=new SysRole();
        $roles =  $role_model->getRoles($user_id);//获取用户组
        if(empty($roles)) return false;

        $node_array = [];
        $permission_model=new SysPermission();
        foreach ($roles as $role) {
            list($node,$permissions) = $permission_model->getPermissions($role->id);
            $node_array = array_merge($node_array,$node);
        }

        $data['checkedKeys']=$node_array;
        $data['menus']=$permission_model->getAllPermission();
        return ajax_output(200,"成功",$data);
    }


    /**
     * 删除用户
     * @param Request $request
     * @param $ids
     * @return void
     */
    public function destroy(Request $request,$id){
        $ids=explode(",",$id);
        foreach($ids as $user_id){
            //删除用户权限
            $role_model=new SysRole();
            $role_model->delRoles($user_id);
        }
        //删除用户
        $admin_model=new Admins();
        $admin_model->destroy($ids);
        return ajax_output(200,"成功");
    }

    /**
     * 首页统计信息
     * @return void
     */
    public function statistics(Request $request){
        $begin_at=date("Y-m-d 00:00:00");
        $end_at=date("Y-m-d 23:59:59");
        $data=[
            'today_register'=>Player::whereBetween('created_at',[$begin_at,$end_at])->count("*"),
            'today_pay'=>PlayerRecharge::whereBetween('created_at',[$begin_at,$end_at])->where('state',1)->sum('money'),
            'merchant_num'=>MerchantInfo::count("*"),
            'game_num'=>MerchantGames::where("state",1)->count("*"),
            'work_order_pending'=>WorkQuestion::whereIn('state',[3,4])->count("*"),
            'task_pending'=>GameTask::where('state',0)->count("*"),
            'server_num'=>MerchantServers::count("*"),
            'game_area_num'=>GameArea::count("*")
        ];
        return ajax_output(200,"成功",$data);
    }
}
